package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;

import android.app.Dialog;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.Html;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemLongClickListener;
import com.stark.picselect.config.PhotoConfig;
import com.stark.picselect.entity.SelectMediaEntity;
import com.stark.picselect.utils.MediaLoadManager;

import java.util.ArrayList;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.adapter.SelPictureAdapter;
import flc.ast.databinding.ActivityPicManageBinding;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.utils.FileUtil;
import stark.common.basic.utils.IntentUtil;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.StkPermissionHelper;

public class PicManageActivity extends BaseAc<ActivityPicManageBinding> {

    private SelPictureAdapter pictureAdapter;
    private List<SelectMediaEntity> listDelete = new ArrayList<>();
    private Dialog myDeleteDialog;
    private boolean isEdit = false;
    private boolean isSelectAll = false;

    @Override
    protected int onCreate() {
        return R.layout.activity_pic_manage;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(this, mDataBinding.event1Container);

        mDataBinding.ivPicManageBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        mDataBinding.rvPicList.setLayoutManager(new GridLayoutManager(mContext, 3));
        pictureAdapter = new SelPictureAdapter();
        mDataBinding.rvPicList.setAdapter(pictureAdapter);
        pictureAdapter.setOnItemClickListener(this);
        pictureAdapter.setOnItemLongClickListener(new OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                if (!isEdit) {
                    isEdit = true;
                    pictureAdapter.setEdit(isEdit);
                    pictureAdapter.notifyDataSetChanged();
                    mDataBinding.tvSelNum.setVisibility(View.VISIBLE);
                    mDataBinding.llPicManageBottom.setVisibility(View.VISIBLE);
                } else {
                    listDelete.clear();
                    isEdit = false;
                    pictureAdapter.setEdit(isEdit);
                    getData();
                    mDataBinding.tvSelNum.setText(getString(R.string.sel_num, listDelete.size()));
                    mDataBinding.tvSelNum.setVisibility(View.GONE);
                    mDataBinding.llPicManageBottom.setVisibility(View.GONE);
                }
                return true;
            }
        });
        mDataBinding.llSelectAll.setOnClickListener(this);
        mDataBinding.llDelete.setOnClickListener(this);
        mDataBinding.llShare.setOnClickListener(this);
        //删除弹框
        deleteDialog();
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.llSelectAll://全选
                listDelete.clear();
                if (isSelectAll) {
                    for (SelectMediaEntity validDatum : pictureAdapter.getValidData()) {
                        validDatum.setChecked(false);
                    }
                } else {
                    for (SelectMediaEntity validDatum : pictureAdapter.getValidData()) {
                        validDatum.setChecked(true);
                        listDelete.add(validDatum);
                    }
                }
                isSelectAll();
                pictureAdapter.notifyDataSetChanged();
                break;
            case R.id.llDelete://删除
                if (listDelete.size() == 0) {
                    return;
                }
                myDeleteDialog.show();
                break;
            //删除弹框
            case R.id.tvDialogDeleteConfirm:
                myDeleteDialog.dismiss();
                delete();
                break;
            case R.id.tvDialogDeleteCancel:
                myDeleteDialog.dismiss();
                break;
            case R.id.llShare://分享
                share();
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        if (isEdit) {
            if (pictureAdapter.getItem(position).isChecked()) {
                pictureAdapter.getItem(position).setChecked(false);
                listDelete.remove(pictureAdapter.getItem(position));
                pictureAdapter.notifyDataSetChanged();
            } else {
                listDelete.add(pictureAdapter.getItem(position));
                pictureAdapter.getItem(position).setChecked(true);
                pictureAdapter.notifyDataSetChanged();
            }
            isSelectAll();
        } else {
            ImgDetailActivity.imgPath = pictureAdapter.getItem(position).getPath();
            startActivity(ImgDetailActivity.class);
        }
    }

    @Override
    protected void initData() {
        mDataBinding.tvSelNum.setVisibility(View.GONE);
        mDataBinding.tvSelNum.setText(getString(R.string.sel_num, 0));
        getPermission();
    }

    private void getPermission() {
        StkPermissionHelper.permission(StkPermissionHelper.Permission.ACCESS_IMAGE_VIDEO)
                .reqPermissionDesc(getString(R.string.get_picture_permission))
                .callback(new StkPermissionHelper.ACallback() {
                    @Override
                    public void onGranted() {
                        getData();
                    }

                    @Override
                    public void onDenied(boolean needGoSettings) {
                        mDataBinding.rvPicList.setVisibility(View.GONE);
                        mDataBinding.ivPicManageNoData.setVisibility(View.VISIBLE);
                    }
                }).request();
    }

    //获取视频和图片数据
    private void getData() {
        RxUtil.create(new RxUtil.Callback<List<SelectMediaEntity>>() {
            @Override
            public void doBackground(ObservableEmitter<List<SelectMediaEntity>> emitter) {
                List<SelectMediaEntity> listSys = MediaLoadManager.loadAllMediaData(mContext, PhotoConfig.Mode.PHOTO);
                emitter.onNext(listSys);
            }

            @Override
            public void accept(List<SelectMediaEntity> selectMediaEntities) {
                if (selectMediaEntities.size() > 0) {
                    pictureAdapter.setList(selectMediaEntities);
                    mDataBinding.rvPicList.setVisibility(View.VISIBLE);
                    mDataBinding.ivPicManageNoData.setVisibility(View.GONE);
                } else {
                    mDataBinding.rvPicList.setVisibility(View.GONE);
                    mDataBinding.ivPicManageNoData.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    private void isSelectAll() {
        mDataBinding.tvSelNum.setText(getString(R.string.sel_num, listDelete.size()));
        if (listDelete.size() == pictureAdapter.getValidData().size()) {
            mDataBinding.ivSelectAll.setImageResource(R.drawable.ayiquanx);
            isSelectAll = true;
        } else {
            mDataBinding.ivSelectAll.setImageResource(R.drawable.aquanx);
            isSelectAll = false;
        }
    }

    private void delete() {
        showDialog(getString(R.string.delete_ing));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                RxUtil.create(new RxUtil.Callback<String>() {

                    @Override
                    public void doBackground(ObservableEmitter<String> emitter) {
                        for (int i = 0; i < listDelete.size(); i++) {
                            //从此文件夹删除
                            mContext.getContentResolver().delete(Uri.parse(listDelete.get(i).getUri()), null, null);
                        }
                        emitter.onNext("");
                    }

                    @Override
                    public void accept(String path) {
                        listDelete.clear();
                        isEdit = false;
                        pictureAdapter.setEdit(isEdit);
                        getData();
                        dismissDialog();
                        ToastUtils.showShort(getString(R.string.delete_suc));
                        mDataBinding.tvSelNum.setText(getString(R.string.sel_num, listDelete.size()));
                        mDataBinding.tvSelNum.setVisibility(View.GONE);
                        mDataBinding.llPicManageBottom.setVisibility(View.GONE);
                    }
                });
            }
        }, 1000);
    }

    private void share() {
        if (listDelete.size() == 0) {
            return;
        }
        List<String> picPathList = new ArrayList<>();
        for (SelectMediaEntity selectMediaEntity : listDelete) {
            picPathList.add(selectMediaEntity.getPath());
        }
        IntentUtil.shareImagesPath(mContext, picPathList);
    }

    //删除弹框
    private void deleteDialog() {
        myDeleteDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_delete, null);
        myDeleteDialog.setContentView(inflate);
        myDeleteDialog.setCancelable(true);
        Window dialogWindow = myDeleteDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.CENTER);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.8);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        TextView cancel = inflate.findViewById(R.id.tvDialogDeleteCancel);
        TextView comp = inflate.findViewById(R.id.tvDialogDeleteConfirm);
        TextView tip = inflate.findViewById(R.id.tvDialogDeleteTip);
        // 设置文本及其颜色
        StringBuffer str = new StringBuffer();
        str.append(getString(R.string.delete_tip1));
        str.append("<font color='#FF3838'>" + getString(R.string.delete_tip2) + "</font>");
        str.append(getString(R.string.delete_tip3));
        // 在文本控件中显示
        tip.setText(Html.fromHtml(str.toString(), getImageGetter(), null));
        cancel.setOnClickListener(this);
        comp.setOnClickListener(this);
    }

    private Html.ImageGetter getImageGetter() {
        return source -> {
            Drawable drawable = getDrawable(Integer.parseInt(source));
            drawable.setBounds(0, 0, 60, 60);
            return drawable;
        };
    }

}